package com.pan.games.threadgame;

import java.util.concurrent.*;

/**
 *
 * JAVA多线程实现方式主要有三种：
 * 继承Thread类、实现Runnable接口、使用ExecutorService、Callable、Future实现有返回结果的多线程。
 * 其中前两种方式线程执行完后都没有返回值，只有最后一种是带返回值的。
 * @author by panstark
 * @description
 * @notice
 * @date 2020/12/15
 */
public class CallableThread  implements Callable {

    private String threadName ;

    public CallableThread(String threadName) {
        this.threadName = threadName;
    }

    @Override
    public Object call() throws Exception {
        return threadName + "返回的信息";
    }


    public static void main(String[] args) {

        //创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(3) ;

        //创建三个有返回值的任务
        CallableThread callableTest1 = new CallableThread("我是线程1") ;
        CallableThread callableTest2 = new CallableThread("我是线程2") ;
        CallableThread callableTest3 = new CallableThread("我是线程3") ;

        Future future1 = pool.submit(callableTest1) ;
        Future future2 = pool.submit(callableTest2) ;
        Future future3 = pool.submit(callableTest3) ;

        try {
            System.out.println(future1.get().toString());
            System.out.println(future2.get().toString());
            System.out.println(future3.get().toString());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }finally{
            pool.shutdown();
        }
    }
}
